import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import MainLayout from '../layouts/MainLayout';
import SecondaryLayout from '../layouts/SecondaryLayout';
import { showToast } from 'vant';
import { store } from '@/store/store';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: SecondaryLayout,
    children: [
      {
        path: 'login',
        name: 'login',
        component: () => import('../views/login'),
        meta: { title: '登录' }
      },
      {
        path: 'register',
        name: 'register',
        component: () => import('../views/login/register'),
        meta: { title: '注册' }
      },
      {
        path: 'verify',
        name: 'verify',
        component: () => import('../views/verify'),
        meta: { title: '实名认证' }
      },
      {
        path: 'product/:id',
        name: 'product',
        component: () => import('../views/product/[id]'),
        meta: { title: '商品详情' }
      }
    ]
  },
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('../views/home')
      },
      {
        path: 'cart',
        name: 'cart',
        component: () => import('../views/cart'),
        meta: { requiresVerification: true }
      },
      {
        path: 'my',
        name: 'my',
        component: () => import('../views/my')
      }
    ]
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

// 路由守卫
router.beforeEach(async (to) => {
  const mainStore = store();
  const isAuthenticated = localStorage.getItem('token');
  const publicPages = ['/login', '/register'];
  const authRequired = !publicPages.includes(to.path);
  
  // 如果是登录页面且已登录，直接跳转到首页
  if (to.path === '/login' && isAuthenticated) {
    return '/';
  }
  
  // 显示 loading
  mainStore.setLoading(true);
  
  try {
    // 检查版本
    await mainStore.checkVersion();
    
    // 如果需要登录且已登录，获取用户信息
    if (authRequired && isAuthenticated) {
      await mainStore.getUserInfo();
      
      // 检查是否需要实名认证
      if (to.meta.requiresVerification && !mainStore.userInfo?.isVerified) {
        showToast({ type: 'fail', message: '该功能需要实名认证' });
        await new Promise(resolve => setTimeout(resolve, 2000));
        return '/verify';
      }
    }
    
    if (authRequired && !isAuthenticated) {
      showToast({ type: 'fail', message: '请先登录' });
      return {
        path: '/login',
        query: { redirect: to.fullPath }
      };
    }
  } finally {
    // 隐藏 loading
    mainStore.setLoading(false);
  }
  
  // 允许导航继续
  return true;
});

export default router;